﻿using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MOKA.TPM.Entity;
using MOKA.TPM.Utility;
using MOKA.TPM.Utility.Const;
using NetTaste;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System.ComponentModel;
using System.Web;

namespace MOKA.TPM.Service;

/// <summary>
/// 定时任务
/// </summary>
[ApiDescriptionSettings(TPMConst.GroupName, Order = 1860)]
public class Service_Doc_Job : IDynamicApiController, ITransient
{
    private IHttpContextAccessor _accessor;//获取请求上下文
    private readonly UserManager _userManager;
    private Service_CheckupReports _service_CheckupReports;
    private readonly ISqlSugarClient _db;

    public Service_Doc_Job(IHttpContextAccessor accessor, UserManager userManager, Service_CheckupReports service_CheckupReports, ISqlSugarClient db)
    {
        _accessor = accessor;
        _userManager = userManager;
        _service_CheckupReports = service_CheckupReports;
        _db = db;
    }

    /// <summary>
    /// 给到点检员的提醒
    /// </summary>
    /// <param name="dy"></param>
    /// <returns></returns>
    [DisplayName("给到点检员的提醒")]
    [AllowAnonymous]
    public async Task<string> GetQtyCheckup([FromQuery] string? ManagerNo, [FromQuery] string CheckupCycleName)
    {
        var ret = "";
        if (string.IsNullOrEmpty(CheckupCycleName))
            throw new ArgumentNullException("点检周期不能为空，可为每日/每周");

        //计算当前周期
        var currentCycle = "";

        if (CheckupCycleName == "每日")
        {
            currentCycle = DateHelper.GetCurrentDateString();
        }
        else if (CheckupCycleName == "每周")
        {
            currentCycle = DateHelper.GetYearMonthWeekString(DateTime.Now);
        }
        else
        {
            throw new ArgumentNullException("点检周期不能为空，可为每日/每周");
        }

        var to_checkup = await _service_CheckupReports.GetQtyCheckup(null, null, CheckupCycleName);
        var checkuped = await _service_CheckupReports.GetQtyCheckuped(null, currentCycle, null, CheckupCycleName);

        var result = from p in to_checkup
                     join _p2 in checkuped
                     on new { p.CheckupCycle, Key1 = p.ManagerNo } equals new { CheckupCycle = (_p2 == null ? null : _p2.CheckupCycle), Key1 = _p2 == null ? null : _p2.CheckupMan } into tmp1
                     from p2 in tmp1.DefaultIfEmpty()
                     where p2 == null || (p2.CurrentCycle != null && p2.CurrentCycle == currentCycle)
                     select new
                     {
                         p.CheckupCycle,
                         p.CheckupCycleName,
                         p.ManagerNo,
                         p.EmployeeName,
                         p.DepartmentName,
                         to_checkupQty = p.Count,//需点检的设备数
                         checkupedQty = p2 == null ? 0 : p2.Count, //已点检的设备数量
                         not_checkupQty = p.Count - (p2 == null ? 0 : p2.Count)//未点检的设备数
                     };

        foreach (dynamic to_checkup_item in result)
        {
            // (JArray.Parse(JsonConvert.SerializeObject(data))
            var to_checkupQty = to_checkup_item.to_checkupQty;//需点检的设备数
            var checkupedQty = to_checkup_item.checkupedQty;
            var not_checkupQty = to_checkupQty - checkupedQty;//未点检的设备数

            if (not_checkupQty <= 0)
            {
                continue;//已完成点检，不需要提醒了
            }

            var desc = not_checkupQty <= 0 ? "恭喜，已完成所有设备点检！" : $"还有 {not_checkupQty} 台设备未点检，请及时处理！";

            //给每个管理员分别推送不同的内容
            string paramJson = JsonConvert.SerializeObject(new
            {
                TITLE = $"TPM【{to_checkup_item.CheckupCycleName}点检】您还有{not_checkupQty}台设备未点检!",
                BINTXT = "查看详情",
                DESCRIPTION = $"{to_checkup_item.EmployeeName}， 您好！" +
                $"\n设备【{to_checkup_item.CheckupCycleName}点检 - {currentCycle}】提醒： " +
                $"\n截止到 {DateTime.Now.ToShortTimeString()} 分, 您已完成点检的设备： {checkupedQty} / {to_checkupQty} 台。" +
                $"\n{desc}",
                TOUSER = to_checkup_item.ManagerNo,
                URL = "Javascript:void(0);"
            });
            var retString = (new HttpClientHelper()).Post("http://10.222.16.22/SMESCommAPI/api/HR/HRDataExchage",
                       JsonConvert.SerializeObject(new
                       {
                           Token = "MOKASMES&OA2021!@#",
                           method = "WxMessageLink",
                           paramJson
                       }
                     )
            );
            if ((bool)JObject.Parse(retString)["Result"] == true)
            {
                ret += $"给 {to_checkup_item.EmployeeName} 信息发送成功，标题：{desc}。";
            }
        }
        return ret;
    }

    /// <summary>
    /// 给到小组长的信息
    /// </summary>
    /// <param name="dy"></param>
    /// <returns></returns>
    [DisplayName("给到小组长的信息")]
    [AllowAnonymous]
    public async Task<string> GetQtyCheckupToGroup([FromQuery] string? ManagerNo, [FromQuery] string CheckupCycleName)
    {
        var ret = "";
        if (string.IsNullOrEmpty(CheckupCycleName))
            throw new ArgumentNullException("点检周期不能为空，可为每日/每周");

        //计算当前周期
        var currentCycle = "";

        if (CheckupCycleName == "每日")
        {
            currentCycle = DateHelper.GetCurrentDateString();
        }
        else if (CheckupCycleName == "每周")
        {
            currentCycle = DateHelper.GetYearMonthWeekString(DateTime.Now);
        }
        else
        {
            throw new ArgumentNullException("点检周期不能为空，可为每日/每周");
        }

        var to_checkup = await _service_CheckupReports.GetQtyCheckup(null, null, CheckupCycleName);
        var checkuped = await _service_CheckupReports.GetQtyCheckuped(null, currentCycle, null, CheckupCycleName);

        var result = (from p in to_checkup
                      join _p2 in checkuped
                      on new { p.CheckupCycle, Key1 = p.ManagerNo } equals new { CheckupCycle = (_p2 == null ? null : _p2.CheckupCycle), Key1 = _p2 == null ? null : _p2.CheckupMan } into tmp1
                      from p2 in tmp1.DefaultIfEmpty()
                      where p2 == null || (p2.CurrentCycle != null && p2.CurrentCycle == currentCycle)
                      select new
                      {
                          p.CheckupCycle,
                          p.CheckupCycleName,
                          p.ManagerNo,
                          p.EmployeeName,
                          p.DepartmentName,
                          to_checkupQty = p.Count,//需点检的设备数
                          checkupedQty = p2 == null ? 0 : p2.Count, //已点检的设备数量
                          not_checkupQty = p.Count - (p2 == null ? 0 : p2.Count)//未点检的设备数
                      })
                    .ToLookup(p => p.DepartmentName);
        string managerNo = "";
        string managerName = ""; ;

        foreach (var lookup in result) //循环每个部门的情况。
        {
            Console.Write($"{lookup.Key}:\t");
            //先写死
            switch (lookup.Key)
            {
                case "中国制造中心智能总装二厂TPM室MNT组":
                    managerNo = "jialiang.li";
                    managerName = "李嘉良";
                    break;

                case "中国制造中心智能总装二厂TPM室SMT组":
                    managerNo = "huangwei.zhou";
                    managerName = "周黄尉";
                    break;

                case "中国制造中心智能总装二厂TPM室DIP组":
                    managerNo = "lijiang1";
                    managerName = "李江";
                    break;

                case "中国制造中心智能总装一厂生产部设备保全室-设备TPM组":
                    managerNo = "zhanghz";
                    managerName = "张焕燥";
                    break;
            }

            string desc = "未完成点检情况如下：";
            foreach (var checkup in lookup)
            {
                if (checkup.not_checkupQty <= 0)
                {
                    continue;//已完成点检，不需要提醒了
                }
                desc += $"{checkup.EmployeeName}：{checkup.not_checkupQty} \t；";
            }
            if (desc == "")
            {
                continue;
            }

            //给每个管理员分别推送不同的内容
            string paramJson = JsonConvert.SerializeObject(new
            {
                TITLE = $"TPM【{CheckupCycleName}点检】还有{lookup.Sum(p => p.not_checkupQty)} 台设备未点检!",
                BINTXT = "查看详情",
                DESCRIPTION = $"{managerName}， 您好！" +
                $"\n设备【{CheckupCycleName}点检 - {currentCycle}】汇报： " +
                $"\n截止到 {DateTime.Now.ToShortTimeString()} 分, 已完成点检的设备： {lookup.Sum(p => p.checkupedQty)} / {lookup.Sum(p => p.to_checkupQty)} 台。" +
                $"\n{desc}",
                TOUSER = managerNo,
                URL = "Javascript:void(0);"
            });
            var retString = (new HttpClientHelper()).Post("http://10.222.16.22/SMESCommAPI/api/HR/HRDataExchage",
                       JsonConvert.SerializeObject(new
                       {
                           Token = "MOKASMES&OA2021!@#",
                           method = "WxMessageLink",
                           paramJson
                       }
                     )
            );
            if ((bool)JObject.Parse(retString)["Result"] == true)
            {
                ret += $"给 {managerName} 信息发送成功，标题：{desc}。";
            }
        }

        return ret;
    }

    public class DateHelper
    {
        // 获取当前年月日字符串
        public static string GetCurrentDateString()
        {
            DateTime today = DateTime.Today;
            string year = today.Year.ToString();
            string month = today.Month.ToString("D2"); // 使用"D2"格式化为两位数
            string day = today.Day.ToString("D2");

            return $"{year}{month}{day}";
        }

        // 获取当年周字符串
        public static string GetYearMonthWeekString(DateTime date)
        {
            int year = date.Year;
            string month = date.Month.ToString("D2");

            // 获取本月第一天和它是星期几
            DateTime firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
            int firstDayWeekday = (int)firstDayOfMonth.DayOfWeek; // 获取本月第一天是星期几（0-6，周日为0）

            // 计算本月第一周的天数
            int firstWeekDays = 7 - firstDayWeekday + 1;

            // 如果第一周的天数小于等于4天，则从第二周开始计数
            int weekNumber;
            if (firstWeekDays <= 4)
            {
                // 计算当前日期是本月的第几周，减去第一周的天数
                int adjustedDate = date.Day - firstWeekDays;
                weekNumber = (int)Math.Ceiling(adjustedDate / 7.0);
            }
            else
            {
                // 正常计算周数
                int adjustedDate = date.Day + firstDayWeekday;
                weekNumber = (int)Math.Ceiling(adjustedDate / 7.0);
            }

            return $"{year}{month}-W{weekNumber}";
        }
    }
}